package edu.algorithm.knn.parallel.impl;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;

import edu.algorithm.knn.parallel.common.Config;
import edu.algorithm.knn.parallel.common.DataPoint;
import edu.algorithm.knn.parallel.common.FileOperator;
import edu.algorithm.knn.parallel.exception.ParrallelKNNException;

/**
 * 测试数据并行KNN
 * 
 * @author liukun
 *
 */
public class KNNParallel {

	/**
	 * 获得数据
	 * 
	 * @return
	 * @throws FileNotFoundException
	 * @throws ParrallelKNNException
	 */
	public static List<DataPoint> getDataPoints(String dataPath, String labelPath)
			throws FileNotFoundException, ParrallelKNNException {
		FileOperator fileOperator = new FileOperator(dataPath, labelPath);

		List<DataPoint> trainDatas = new ArrayList<>();
		while (fileOperator.hasData()) {
			String[] strainData = fileOperator.next();
			trainDatas.add(DataPoint.getOnePoint(strainData[0], strainData[1]));
		}
		return trainDatas;
	}

	public static void main(String[] args) throws FileNotFoundException, ParrallelKNNException {
		// 获得训练数据
		List<DataPoint> trainDataList = getDataPoints(Config.DATA_FILE_PATH, Config.LABLE_FILE_PATH);
		// 获得测试数据
		List<DataPoint> testDataList = getDataPoints(Config.DATA2_FILE_PATH, Config.LABLE2_FILE_PATH);
		DataPoint[] testDataPoints = new DataPoint[testDataList.size()];
		int i = 0;
		for (DataPoint dataPoint : testDataList) {
			testDataPoints[i] = dataPoint;
			i++;
		}
		testDataList = null;
		// fork join 线程池
		ForkJoinPool forkjoinpool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());
		int K = 40;
		KNN knn = new KNN(testDataPoints, 0, testDataPoints.length - 1, trainDataList, K);
		long begintime = System.currentTimeMillis();
		forkjoinpool.invoke(knn);
		long endtime = System.currentTimeMillis();
		System.out.println("一共耗时:" + (endtime - begintime));
	}

}
